﻿<template>
  <div class="xuankeTask-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="queryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="选课任务名称">
              <el-input v-model="queryParams.name" clearable="" placeholder="请输入选课任务名称"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="开始时间">
              <el-date-picker placeholder="请选择开始时间" value-format="YYYY/MM/DD" type="daterange" v-model="queryParams.startTimeRange" />
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="结束时间">
              <el-date-picker placeholder="请选择结束时间" value-format="YYYY/MM/DD" type="daterange" v-model="queryParams.endTimeRange" />
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="启用">
              <el-select v-model="queryParams.active" placeholder="请选择结束是否启用">
                <el-option v-for="item in activeOptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="级">
              <el-input-number v-model="queryParams.ji"  clearable="" placeholder="请输入级"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="状态">
              <el-select clearable="" v-model="queryParams.status" placeholder="请选择状态">
                <el-option v-for="(item,index) in dl('xuanke_status')" :key="index" :value="item.code" :label="`[${item.code}] ${item.value}`" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="备注">
              <el-input v-model="queryParams.remark" clearable="" placeholder="请输入备注"/>
              
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" class="mb10">
            <el-form-item>
              <el-button-group>
                <el-button type="primary"  icon="ele-Search" @click="handleQuery" v-auth="'xuankeTask:page'"> 查询 </el-button>
                <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
                <el-button icon="ele-ZoomIn" @click="changeAdvanceQueryUI" v-if="!showAdvanceQueryUI"> 高级 </el-button>
                <el-button icon="ele-ZoomOut" @click="changeAdvanceQueryUI" v-if="showAdvanceQueryUI"> 隐藏 </el-button>
                
              </el-button-group>
              
              <el-button-group style="margin-left:20px">
                <el-button type="primary" icon="ele-Plus" @click="openAddXuankeTask" v-auth="'xuankeTask:add'"> 新增 </el-button>
                
              </el-button-group>
              
            </el-form-item>
            
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 8px">
      <el-table
				:data="tableData"
				style="width: 100%"
				v-loading="loading"
				tooltip-effect="light"
				row-key="id"
				border="">
        <el-table-column type="index" label="序号" width="55" align="center"/>
        <el-table-column prop="name" label="选课任务名称" width="200" show-overflow-tooltip="" />
        <el-table-column prop="startTime" label="开始时间" width="140" show-overflow-tooltip="" />
        <el-table-column prop="endTime" label="结束时间" width="140" show-overflow-tooltip="" />
        <el-table-column prop="active" label="启用" width="120" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag v-if="scope.row.active"> 是 </el-tag>
            <el-tag type="danger" v-else> 否 </el-tag>
            
          </template>
          
        </el-table-column>
        <el-table-column prop="ji" label="级" width="140" show-overflow-tooltip="" />
          <el-table-column prop="status" label="状态" width="140" show-overflow-tooltip="" >
            <template #default="scope">
              <el-tag :type="di('xuanke_status', scope.row.status)?.tagType"> {{di("xuanke_status", scope.row.status)?.value}} </el-tag>
            </template>
          </el-table-column>
        <el-table-column prop="remark" label="备注" width="140" show-overflow-tooltip="" />
        <el-table-column label="操作" width="400" align="center" fixed="right" show-overflow-tooltip="" v-if="auth('xuankeTask:edit') || auth('xuankeTask:delete')">
          <template #default="scope">
            <el-button icon="ele-Printer" size="small" text="" type="primary" @click="initXuankeTaskHandle(scope.row)" v-auth="'xuankeTask:init'"> 初始化选课任务 </el-button>
            <el-button icon="ele-Printer" size="small" text="" type="primary" @click="openUploadDialog(scope.row)" v-auth="'xuankeTask:import'"> 预选导入 </el-button>
            <el-button icon="ele-Edit" size="small" text="" type="primary" @click="openEditXuankeTask(scope.row)" v-auth="'xuankeTask:edit'"> 编辑 </el-button>
            <el-button icon="ele-Delete" size="small" text="" type="primary" @click="delXuankeTask(scope.row)" v-auth="'xuankeTask:delete'"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
				v-model:currentPage="tableParams.page"
				v-model:page-size="tableParams.pageSize"
				:total="tableParams.total"
				:page-sizes="[10, 20, 50, 100, 200, 500]"
				small=""
				background=""
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper"
	/>
      <printDialog
        ref="printDialogRef"
        :title="printXuankeTaskTitle"
        @reloadTable="handleQuery" />
      <editDialog
        ref="editDialogRef"
        :title="editXuankeTaskTitle"
        @reloadTable="handleQuery"
      />
      <el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action="" :on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
            <el-link @click="download">导入模板下载</el-link>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts" setup="" name="xuankeTask">
  import { ref,reactive } from "vue";
  import { ElMessageBox, ElMessage,UploadInstance } from "element-plus";
  import { auth } from '/@/utils/authFunction';
  import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
  import { formatDate } from '/@/utils/formatTime';

  // 推荐设置操作 width 为 200
  import { hiprint } from 'vue-plugin-hiprint';
  import { SysPrintApi } from '/@/api-services/api';
  import { SysPrint } from '/@/api-services/models';

  import { getAPI } from '/@/utils/axios-utils';
  import { SysFileApi } from '/@/api-services/api';
  import { SysFile } from '/@/api-services/models';
  import { downloadByUrl, downloadByData, getFileName } from '/@/utils/download';

  import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
  import editDialog from '/@/views/main/xuankeTask/component/editDialog.vue'
  import { pageXuankeTask, deleteXuankeTask,initXuankeTask,importXuankeTask } from '/@/api/main/xuankeTask';

  const uploadRef = ref<UploadInstance>();
  const state = reactive({
    loading: false,
    fileData: [] as Array<SysFile>,
    queryParams: {
      fileName: undefined,
      startTime: undefined,
      endTime: undefined,
    },
    tableParams: {
      page: 1,
      pageSize: 10,
      total: 0 as any,
    },
    dialogUploadVisible: false,
    diaglogEditFile: false,
    fileList: [] as any,
    dialogDocxVisible: false,
    dialogXlsxVisible: false,
    dialogPdfVisible: false,
    dialogImportVisible: false,
    showViewer: false,
    docxUrl: '',
    excelUrl: '',
    pdfUrl: '',
    fileName: '',
    previewList: [] as string[],
  });

  const showAdvanceQueryUI = ref(false);
  const printDialogRef = ref();
  const editDialogRef = ref();
  const loading = ref(false);
  const tableData = ref<any>([]);
  const queryParams = ref<any>({});
  const tableParams = ref({
    page: 1,
    pageSize: 10,
    total: 0,
  });
  const activeOptions= ref([
    {label: "全部",value: -1},
    {label: "启用",value: 1},
    {label: "禁用",value: 0},
  ]);
  const printXuankeTaskTitle = ref("");
  const editXuankeTaskTitle = ref("");
  const xuankeTaskId = ref(0);
  
  // 改变高级查询的控件显示状态
  const changeAdvanceQueryUI = () => {
    showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
  }
  

  // 查询操作
  const handleQuery = async () => {
    loading.value = true;
    var res = await pageXuankeTask(Object.assign(queryParams.value, tableParams.value));
    tableData.value = res.data.result?.items ?? [];
    tableParams.value.total = res.data.result?.total;
    loading.value = false;
  };

  // 打开新增页面
  const openAddXuankeTask = () => {
    editXuankeTaskTitle.value = '添加选课任务';
    editDialogRef.value.openDialog({});
  };

  // 打开打印页面
  const openPrintXuankeTask = async (row: any) => {
    printXuankeTaskTitle.value = '打印选课任务';
    var res = await getAPI(SysPrintApi).apiSysPrintPrintNameGet('各班学生名单');
	  var printTemplate = res.data.result as SysPrint;
    var template = JSON.parse(printTemplate.template);
    row['printDate'] = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')
    printDialogRef.value.showDialog(new hiprint.PrintTemplate({template: template}), row, template.panels[0].width);
  }
  
  // 打开编辑页面
  const openEditXuankeTask = (row: any) => {
    editXuankeTaskTitle.value = '编辑选课任务';
    editDialogRef.value.openDialog(row);
  };

  // 删除
  const delXuankeTask = (row: any) => {
    ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(async () => {
    await deleteXuankeTask(row);
    handleQuery();
    ElMessage.success("删除成功");
  })
  .catch(() => {});
  };

  // 改变页面容量
  const handleSizeChange = (val: number) => {
    tableParams.value.pageSize = val;
    handleQuery();
  };

  // 改变页码序号
  const handleCurrentChange = (val: number) => {
    tableParams.value.page = val;
    handleQuery();
  };

  const initXuankeTaskHandle  = async (row: any) => {
    loading.value = true;
    await initXuankeTask({id:row.id});
    ElMessage.success("选课任务初始化成功");
    loading.value = false;
  }
  
  // 打开上传页面
  const openUploadDialog = async (row: any)  => {
    xuankeTaskId.value = row.id;
    state.fileList = [];
    state.dialogUploadVisible = true;
  };
  // 通过onChanne方法获得文件列表
  const handleChange = (file: any, fileList: []) => {
    state.fileList = fileList;
  };

  // 上传
  const uploadFile = async () => {
    if (state.fileList.length < 1) return;
    var res = await getAPI(SysFileApi).apiSysFileUploadFilePostForm(state.fileList[0].raw);
    ElMessage.success('上传成功');
    state.dialogUploadVisible = false;
    loading.value = true;
    var r = await importXuankeTask({xuankeTaskId:xuankeTaskId.value,fileId:res.data.result?.id});
    	// 抛出错误
	// ElMessage.error(msg);
    ElMessage({
      type:'success',
      dangerouslyUseHTMLString:true,
      message:'导入成功:<br/>'+r.data.result
    })

    handleQuery();
    loading.value = false;
  };

  const download = () => {
    let fileUrl = '/download/yuxuan.xlsx';
    downloadByUrl({ url: fileUrl });
  };

  handleQuery();
</script>
<style scoped>
:deep(.el-ipnut),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>

